package com.ellricky.baselib.ui;

import android.content.Intent;
import android.view.View;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.andr.common.http.callback.JOCallback;
import com.andr.common.http.util.JsonUtil;
import com.andr.common.ui.activity.BaseToolBarActivity;
import com.andr.common.ui.mvp.BasePresenter;
import com.andr.common.util.EmptyUtil;
import com.andr.common.widget.refresh.RefreshFlag;
import com.andr.common.widget.refresh.RefreshRvView;
import com.andr.common.widget.refresh.RvRefreshListener;
import com.ellricky.baselib.BaseConstant;
import com.ellricky.baselib.R;
import com.ellricky.baselib.entity.PersonEntity;
import com.ellricky.baselib.entity.PersonItemEntity;
import com.ellricky.baselib.http.Api;
import com.ellricky.baselib.http.HttpUtils;
import com.ellricky.baselib.adapter.PersonAdapter;
import com.ellricky.baselib.listener.PersonListListener;
import com.ellricky.baselib.util.EAppUtil;
import com.flyco.roundview.RoundTextView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PersonChooseActivity
        extends BaseToolBarActivity<Void, BasePresenter<Void>>
        implements RvRefreshListener, PersonListListener {

    private TextView tvChooseNum;
    private RoundTextView tvSubmit;
    protected RefreshRvView rvView;
    protected PersonAdapter adapter;
    protected List<PersonEntity> dataSource = new ArrayList<>();

    protected List<PersonItemEntity> chooseDataList;

    protected List<PersonItemEntity> allPersonList = new ArrayList<>();

    private String apiPath = "";
    private String classId = "";
    private boolean showSex;


    @Override
    public void initUIView() {
        chooseDataList = (List<PersonItemEntity>) getIntent().getSerializableExtra(BaseConstant.KEY_PERSON_LIST);
        if (chooseDataList == null) chooseDataList = new ArrayList<>();

        apiPath = getIntent().getStringExtra("api_path");
        if (EmptyUtil.isEmpty(apiPath)) apiPath = Api.API_PERSON_CHOOSE;
        classId = getIntent().getStringExtra("class_id");
        showSex = getIntent().getBooleanExtra("showSex",false);

        super.initUIView();
        mTvTitle.setText("人员选择");
        mBtnRight.setVisibility(View.VISIBLE);

        tvChooseNum = findViewById(R.id.tvChooseNum);
        tvSubmit = findViewById(R.id.btnSubmit);

        mBtnRight.setText(R.string.base_choose_all);
        tvSubmit.setOnClickListener(this);

        rvView = findViewById(R.id.rvView);
        rvView.init(this, RefreshFlag.NONE);
        rvView.loadContent(true);
    }


    @Override
    public int getContentLayout() {
        return R.layout.base_activity_person_choose;
    }


    @Override
    public void setAdapter(RecyclerView rv) {
        adapter = new PersonAdapter(this, null, this);
        adapter.setChoosePage(true);
        adapter.setShowSex(showSex);
        rv.setAdapter(adapter);
    }

    @Override
    public void loadData(boolean refresh) {
        String url = EAppUtil.getApiHost() + apiPath;
        Map<String, Object> paramMap = new HashMap<>();
        if (!EmptyUtil.isEmpty(classId)) {
            paramMap.put("classId", classId);
        }
        HttpUtils.getInstance().post(url, paramMap, new JOCallback(this) {
            @Override
            public void onSuccess(JSONObject dataJO, String msg) {
                dataSource.clear();
                allPersonList.clear();

                JSONObject realDataJO = dataJO.optJSONObject("data");
                if (realDataJO != null) {
                    String title = realDataJO.optString("title");
                    if (!EmptyUtil.isEmpty(title)) {
                        String[] tArr = title.split(",");

                        for (String t : tArr) {
                            PersonEntity personEntity = new PersonEntity();
                            personEntity.setShortName(t);

                            JSONArray dataA = realDataJO.optJSONArray(t);
                            if (dataA != null) {
                                List<PersonItemEntity> itemList = new ArrayList<>();
                                for (int i = 0; i < dataA.length(); i++) {
                                    PersonItemEntity itemEntity =
                                            JsonUtil.toBean(dataA.optJSONObject(i), PersonItemEntity.class);

                                    if (itemEntity != null) {
                                        itemList.add(itemEntity);
                                        if (chooseDataList.contains(itemEntity)) {
                                            itemEntity.setChecked(true);
                                        }
                                    }
                                }
                                personEntity.setData(itemList);
                                allPersonList.addAll(itemList);
                            }

                            dataSource.add(personEntity);
                        }

                    }
                }


                rvView.onLoadFinish(dataSource, true);

                boolean isAll = curAllState();
                updateRightBtnText(isAll);
                updateNumText();
            }

            @Override
            public void onErrorCode(JSONObject dataJO, String code, String msg) {
                super.onErrorCode(dataJO, code, msg);
                rvView.onRefreshFailed(true);
            }

            @Override
            public void onHttpError(String code, String msg) {
                super.onHttpError(code, msg);
                rvView.onRefreshFailed(true);
            }
        });
    }


    @Override
    public void updateAdapterData(boolean refresh) {
        if (refresh) adapter.refresh(dataSource);
        else adapter.loadMore(dataSource);
    }


    @Override
    public void onClickView(View v) {
        super.onClickView(v);
        if (v == mBtnRight) {
            if (allPersonList.size() <= 0) return;
            notifyAdapter();
        } else if (v == tvSubmit) {
            sendResult();
        }
    }


    private void notifyAdapter() {
        boolean toChooseAll = !curAllState();
        updateRightBtnText(toChooseAll);
        chooseDataList.clear();
        for (int i = 0; i < dataSource.size(); i++) {
            PersonEntity personEntity = dataSource.get(i);
            List<PersonItemEntity> itemEntityList = personEntity.getData();
            for (int j = 0; j < itemEntityList.size(); j++) {
                PersonItemEntity itemEntity = itemEntityList.get(j);
                itemEntity.setChecked(toChooseAll);
                if (toChooseAll) {
                    chooseDataList.add(itemEntity);
                }
            }
        }

        updateNumText();
        adapter.refresh(dataSource);
    }


    @Override
    public void onClickPersonItem(PersonItemEntity itemEntity) {
        if (itemEntity.isChecked()) {
            chooseDataList.add(itemEntity);
        } else {
            chooseDataList.remove(itemEntity);
        }

        updateRightBtnText(curAllState());
        updateNumText();
    }


    /**
     * 判断当前是否是全选状态
     */
    private void updateRightBtnText(boolean chooseAll) {
        if (chooseAll) {
            mBtnRight.setText(R.string.base_choose_all_cancel);
        } else {
            mBtnRight.setText(R.string.base_choose_all);
        }
    }

    private void updateNumText() {
        tvChooseNum.setText(getString(R.string.base_choose_num, chooseDataList.size()));
    }

    private boolean curAllState() {
        return allPersonList.size() > 0 && (allPersonList.size() == chooseDataList.size());
    }

    private void sendResult() {
        Intent intent = new Intent();
        intent.putExtra(BaseConstant.KEY_PERSON_LIST, (Serializable) chooseDataList);
        setResult(BaseConstant.RESULT_CODE_CHOOSE_PERSON, intent);
        finish();
    }


}
